﻿using System;
using Core.Model;
using SharpDX.Game.Debugger;
using SharpDX.Game.View.Builders;
using SharpDX.Game.View.Renders;
using SharpDX.Windows;
using System.Threading;

namespace SharpDX.Game
{
    public class GameCicle:IDisposable
    {
        private World World;

        private bool IsStarted;

        public void Run()
        {
            SharpDxWordRenderer renderer = SharpDxWordRenderer.Create();

            SharpDxSkyDomRenderer skyDomeRenderer = new SharpDxSkyDomRenderer(renderer._device);

            skyDomeRenderer.LoadContent();

            World = new World(renderer, new SharpDxChunkBuilder(renderer._device), skyDomeRenderer, new SharpDxWorldDebugger(renderer._device));

            IsStarted = true;

            try
            {
                ThreadPool.QueueUserWorkItem(UpdateThread);

                RenderLoop.Run(renderer.RenderForm, Cicle);
            }
            finally
            {
                IsStarted = false;
            }
        }

        private void UpdateThread(object obj)
        {
            while (IsStarted)
            {
                var now = DateTime.Now;

                World.Draw();

                var ms = (DateTime.Now - now).Milliseconds;

                Thread.Sleep(Math.Max(0, 1000 / 60 - ms));
            }
        }

        private void Cicle()
        {
            var now =DateTime.Now;

            World.Update();

            var ms = (DateTime.Now - now).Milliseconds;

            Thread.Sleep(Math.Max(0, 1000 / 100 - ms));
        }

        public void Dispose()
        {
        }
    }
}
